package com.moyu.crowdsource.controller;

import com.moyu.crowdsource.entity.AccountUser;
import com.moyu.crowdsource.entity.CommodityImage;
import com.moyu.crowdsource.service.AccountUserService;
import com.moyu.crowdsource.util.Msg;
import com.moyu.crowdsource.util.MyUUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Api(
  value = "用户controller",
  tags = {"用户操作接口"}
)
@RestController
@RequestMapping("${api.base}/accountuser")
@CrossOrigin
public class AccountUserController {

  @Autowired AccountUserService accountUserService;

  @ApiOperation("获取全部用户信息")
  @GetMapping("/getall")
  public Msg getAllAccount() {
    return Msg.success().add("allAccount", accountUserService.getAllAccount());
  }

  @ApiOperation("用户注册")
  @PostMapping("/register")
  public Msg registerAccount(@Valid AccountUser accountUser, BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
      Map<String, Object> map = new HashMap<String, Object>();
      List<FieldError> errors = bindingResult.getFieldErrors();
      for (FieldError fieldError : errors) {
        /*System.out.println("错误字段名" + fieldError.getField());
        System.out.println("错误信息" + fieldError.getDefaultMessage());*/
        map.put(fieldError.getField(), fieldError.getDefaultMessage());
      }
      return Msg.fail().add("errorFields", map);
    }

    accountUser.setIconUrl(
        "https://moyu-storage.oss-cn-qingdao.aliyuncs.com/avatar/define.jpg?x-oss-process=style/moyustyle");
    accountUserService.registerAccount(accountUser);
    return Msg.success().add("info", "注册成功");
  }

  @ApiOperation(value = "检查用户名是否可以注册")
  @GetMapping("/chackuser")
  public Msg chackAccountUsername(String accountUsername) {
    return Msg.success().add("result", accountUserService.chackAccountUsername(accountUsername));
  }

  @ApiOperation(value = "获取当前登录用户信息(最新)")
  @GetMapping("/me")
  public Msg getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {

    AccountUser accountUser = (AccountUser) userDetails;
    Integer userId = Integer.valueOf(accountUser.getUserId());
    return Msg.success().add("me", accountUserService.getAccountInfo(userId));
  }

  @ApiOperation(value = "获取最新用户信息")
  @GetMapping("/account/{userId}")
  public Msg getAccountById(@PathVariable("userId") Integer userId) {
    return Msg.success().add("accountInfo", accountUserService.getAccountInfo(userId));
  }

  @ApiOperation(value = "更新用户信息")
  @PutMapping("/update/{userId}")
  public Msg updateAccount(AccountUser accountUser) {

    accountUserService.updateAccount(accountUser);
    return Msg.success();
  }

  @ApiOperation("用户头像上传")
  @PutMapping("/upload/{userId}")
  public Msg UserIconUpload(MultipartFile multfile, AccountUser accountUser) {
    if (null != multfile && !multfile.isEmpty()) {
      try {
        // 获取文件名
        String fileName = multfile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名，防止生成的临时文件重复
        final File excelFile = File.createTempFile(MyUUID.getUUID32(), prefix);
        // MultipartFile to File
        multfile.transferTo(excelFile);
        accountUserService.uploadUserImage(excelFile, excelFile.getName(), accountUser);
        deleteFile(excelFile);
        return Msg.success().add("info", "文件上传成功");
      } catch (Exception e) {
        return Msg.fail().add("转换文件失败", e);
      }
    }
    return Msg.fail().add("info", "文件为空");
  }

  private void deleteFile(File... files) {
    for (File file : files) {
      if (file.exists()) {
        file.delete();
      }
    }
  }
}
